/**
 * @projectName im-21675-cqmx1
 * @package com.zhang.codec
 * @className com.zhang.codec.ObjDecoder
 * @copyright Copyright 2020 Thunisoft, Inc All rights reserved.
 */
package com.zhang.codec;

import com.zhang.util.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.util.List;

/**
 * ObjDecoder
 * @description 编码器
 * @author zhangjun
 * @date 2025/9/19 下午4:47
 * @version 1.0
 */
public class ObjDecoder extends MessageToMessageDecoder<ByteBuf> {

    private Class<?> genericClass;



    public ObjDecoder(Class<?> genericClass) {

        this.genericClass = genericClass;

    }



    @Override

    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {

        if (in.readableBytes() < 4) {

            return;

        }

        in.markReaderIndex();

        int dataLength = in.readInt();

        if (in.readableBytes() < dataLength) {

            in.resetReaderIndex();

            return;

        }

        byte[] data = new byte[dataLength];

        in.readBytes(data);

        out.add(SerializationUtil.deserialize(data, genericClass));

    }


}
 